package com.ruoyi.common.huanxing;
import java.time.Instant;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.easemob.im.server.EMException;
import com.easemob.im.server.EMService;
import com.easemob.im.server.api.message.send.SendMessage;
import com.easemob.im.server.api.token.Token;
import com.easemob.im.server.model.EMKeyValue;
import com.easemob.im.server.model.EMTextMessage;
import com.easemob.im.server.model.EMUser;
import net.sf.json.JSONObject;

/**
 * 	环信 IM
 * @author liuz
 *
 */
@Component
public class EMServiceUtil {

	@Autowired
	private EMService service;

	/**
	 * 创建用户
	 * @param userName		用户ID
	 * @param pwassword		密码
	 * @return
	 */
	public EMUser createUser(String nickName) {
		try {
			EMUser user = service.user().create(nickName,nickName).block();
			// 设置用户其他属性
			//			if(null != user) {
			//				Map<String, String> map = new HashMap<>();
			//				map.put("nickname", nickName);
			//				map.put("avatar", headPic);
			//				service.metadata().setMetadataToUser(userName, map);
			//			}

			return user;
		} catch (EMException e) {
			e.getErrorCode();
			e.getMessage();
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 	删除用户
	 * @param userName		用户ID
	 * @return
	 */
	public boolean deleteUser(String userName) {
		try {
			service.user().delete(userName).block();
			return true;
		} catch (EMException e) {
			e.getErrorCode();
			e.getMessage();
			e.printStackTrace();
			return false;
		}
	}
	/**
	 * 	发送系统消息
	 * @param title			标题
	 * @param usernames		接受者ID
	 * @return
	 */
	public boolean sendSystemMsg(String title,Set<String> usernames) {
		try {
//			Consumer<Set<EMKeyValue>> customizer = c ->{
//				Iterator<Map.Entry<String,Object>> entries = map.entrySet().iterator();
//				while (entries.hasNext()) {
//					Map.Entry<String,Object> entry = entries.next();
//					c.add(EMKeyValue.of(entry.getKey(), entry.getValue()));
//				}
//			};
			SendMessage send = service.message().send();
			send.fromUser("XT999999").toUsers(usernames)
			.text(msg -> msg.text(title))
			//.extension(customizer)
			.send()
			.block();
			System.out.println("推送成功(无扩展字段)：参数==========================="+JSON.toJSONString(usernames));
			return true;
		} catch (EMException e) {
			e.getErrorCode();
			e.getMessage();
			e.printStackTrace();
			return false;
		}
	}

	/**
	 * 	发送系统消息
	 * @param title			标题
	 * @param usernames		接受者ID
	 * @param map
	 * @return
	 */
	public boolean sendSystemMsg(String title,Set<String> usernames,Map<String,Object> map) {
		try {
			Consumer<Set<EMKeyValue>> customizer = c ->{
				Iterator<Map.Entry<String,Object>> entries = map.entrySet().iterator();
				while (entries.hasNext()) {
					Map.Entry<String,Object> entry = entries.next();
					c.add(EMKeyValue.of(entry.getKey(), entry.getValue()));
				}
			};
			SendMessage send = service.message().send();
			send.fromUser("XT999999").toUsers(usernames)
			.text(msg -> msg.text(title))
			.extension(customizer)
			.send()
			.block();
			System.out.println("推送成功：参数==========================="+JSON.toJSONString(usernames));
			return true;
		} catch (EMException e) {
			e.getErrorCode();
			e.getMessage();
			e.printStackTrace();
			return false;
		}
	}

	/**
	 * 	发送官网消息
	 * @param title			标题
	 * @param usernames		接受者ID
	 * @param map
	 * @return
	 */
	public boolean sendOfficialMsg(String title,Set<String> usernames,Map<String,Object> map) {
		try {
			Consumer<Set<EMKeyValue>> customizer = c ->{
				Iterator<Map.Entry<String,Object>> entries = map.entrySet().iterator();
				while (entries.hasNext()) {
					Map.Entry<String,Object> entry = entries.next();
					c.add(EMKeyValue.of(entry.getKey(), entry.getValue()));
				}
			};
			SendMessage send = service.message().send();
			send.fromUser("GF999999").toUsers(usernames)
			.text(msg -> msg.text(title))
			.extension(customizer)
			.send()
			.block();
			System.out.println("推送成功GF999999：参数==========================="+JSON.toJSONString(usernames));
			return true;
		} catch (EMException e) {
			e.getErrorCode();
			e.getMessage();
			e.printStackTrace();
			return false;
		}
	}
	
//	public boolean sendTextMsg() {
//		 Set<String> toUsers = new HashSet<>();
//		 toUsers.add("toUserName");
//		EMTextMessage textMessage = new EMTextMessage().text("hello-我来测试发送消息");
//		Set<EMKeyValue> exts = new HashSet<>();
//		exts.add(EMKeyValue.of("key", "value"));
//		try {
//		     EMSentMessageIds messageIds = service.message().sendMsg("fromUserName", "users", toUsers, textMessage, exts).block();
//		 } catch (EMException e) {
//		     e.getErrorCode();
//		     e.getMessage();
//		 }
//		return true;
//	}
	public boolean sendUserChat(String form,Set<String> usernames,Map<String,Object> map) {
		try {
			
			Set<EMKeyValue> customizer = new HashSet<EMKeyValue>();
			Iterator<Map.Entry<String,Object>> entries = map.entrySet().iterator();
			while (entries.hasNext()) {
				Map.Entry<String,Object> entry = entries.next();
				customizer.add(EMKeyValue.of(entry.getKey(), entry.getValue()));
			}
//			Consumer<Set<EMKeyValue>> customizer = c ->{
//				Iterator<Map.Entry<String,Object>> entries = map.entrySet().iterator();
//				while (entries.hasNext()) {
//					Map.Entry<String,Object> entry = entries.next();
//					c.add(EMKeyValue.of(entry.getKey(), entry.getValue()));
//				}
//			};
//			SendMessage send = service.message().send();
//			send.fromUser("XT999999").toUsers(usernames)
//			.text(msg -> msg.text(title))
//			.extension(customizer)
//			.send()
//			.block();
			EMTextMessage textMessage = new EMTextMessage().text("你好，我是后台发送的消息呢");
			service.message().send(form, "singleChat", usernames, textMessage, customizer);
			System.out.println("推送成功：参数==========================="+JSON.toJSONString(usernames));
			return true;
		} catch (EMException e) {
			e.getErrorCode();
			e.getMessage();
			e.printStackTrace();
			return false;
		}
	}

	public boolean sendSystemMsg(String from,String title,Set<String> usernames,Map<String,Object> map) {
		try {
			Consumer<Set<EMKeyValue>> customizer = c ->{
				Iterator<Map.Entry<String,Object>> entries = map.entrySet().iterator();
				while (entries.hasNext()) {
					Map.Entry<String,Object> entry = entries.next();
					c.add(EMKeyValue.of(entry.getKey(), entry.getValue()));
				}
			};
			SendMessage send = service.message().send();
			send.fromUser(from).toUsers(usernames)
			.text(msg -> msg.text(title))
			.extension(customizer)
			.send()
			.block();
			System.out.println("后台发送消息成功：参数==========================="+JSON.toJSONString(usernames));
			return true;
		} catch (EMException e) {
			e.getErrorCode();
			e.getMessage();
			e.printStackTrace();
			return false;
		}
	}
	
	/**
	 * 	发送自定义消息
	 * @param formUserId	发送者ID
	 * @param toUserId		接收者ID
	 * @param customEvent	主题
	 * @param map			参数<K,V>
	 * @return
	 */
	public boolean sendCustomMsg(String formUserId,String toUserId,String customEvent,Map<String,Object> map) {
		try {
//			Set<EMKeyValue> set = new HashSet<EMKeyValue>();
//			Iterator<Map.Entry<String,Object>> entries = map.entrySet().iterator();
//			while (entries.hasNext()) {
//				Map.Entry<String,Object> entry = entries.next();
//				set.add(EMKeyValue.of(entry.getKey(), entry.getValue()));
//			}
			Consumer<Set<EMKeyValue>> customizer = c ->{
				Iterator<Map.Entry<String,Object>> entries = map.entrySet().iterator();
				while (entries.hasNext()) {
					Map.Entry<String,Object> entry = entries.next();
					c.add(EMKeyValue.of(entry.getKey(), entry.getValue()));
				}
			};
			SendMessage send = service.message().send();
			send.fromUser(formUserId).toUser(toUserId)
			.custom(msg -> msg.customEvent(customEvent))
			.extension(customizer)
			.send()
			.block();
			System.out.println("消息发送成功");
			return true;
		} catch (EMException e) {
			e.getErrorCode();
			e.getMessage();
			e.printStackTrace();
			return false;
		}
	}

	/**
	 * 	拉黑用户
	 * @param fromUser		被阻止的用户的用户名
	 * @param toUser		接收消息的用户的用户名
	 * @return
	 */
	public boolean blockUser(String fromUser,String toUser) {
		try {
			service.block().blockUserSendMsgToUser(toUser, fromUser).block();
			return true;
		} catch (EMException e) {
			e.printStackTrace();
			return false;
		}
	}

	/**
	 * 	取消拉黑用户
	 * @param fromUser		被阻止的用户的用户名
	 * @param toUser		接收消息的用户的用户名
	 * @return
	 */
	public boolean unblockUser(String fromUser,String toUser) {
		try {
			service.block().unblockUserSendMsgToUser(toUser, fromUser).block();
			return true;
		} catch (EMException e) {
			e.printStackTrace();
			return false;
		}
	}

	/**
	 * 	获取用户在线状态
	 * @param userName
	 * @return
	 */
	public boolean isOnline(String userName) {
		try {
			Boolean isOnline = service.user().isUserOnline(userName).block();
			return isOnline;
		} catch (EMException e) {
			e.printStackTrace();
			return false;
		}
	}

	/**
	 * 	强制用户下线
	 * @param userName
	 * @return
	 */
	public boolean forceLogoutAllDevices(String userName) {
		try {
			service.user().forceLogoutAllDevices(userName).block();
		} catch (EMException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	/**
	 * 	获取APP Token
	 * @return
	 */
	public String getAppToken() {
		try {
			Token block = service.token().getAppToken().block();
			return block.getValue();
		} catch (EMException e) {
			e.getErrorCode();
			e.getMessage();
		}
		return "";
	}
	
	/**
	 * 	删除用户聊天记录
	 * @param userName
	 * @param toUserName
	 */
	public void deleteChannel(String userName,String toUserName) {
		try {
		     service.message().deleteChannel(userName, toUserName, "chat", true).block();
		 } catch (EMException e) {
		     e.getErrorCode();
		     e.getMessage();
		 }
	}
	
	
	/**
	 * 	获取历史消息
	 * @return
	 */
	public String getHistoryAsUri() {
		 Instant now = Instant.parse("2023-10-24T16:00:00.631Z").minusMillis((TimeUnit.HOURS.toMillis(8)));
	     String historyUrl = service.message().getHistoryAsUri(now).block();
	     return historyUrl;
	}

	/**
	 * 	消息撤回
	 * @param token 		appToken YWMtRy5WctqPEeylGEORKlsdjgQfIf__MjPQu-0JvrjULpQU0UQdlNRNh4WlLDFBsiIEAgMAAAGA8MXuUDeeSACyZ0FjISawI6ttLCioJ11YQN7cWccuoOQ9kvC91702Kg
	 * @param msgId			消息ID	1012510754600913652
	 * @param toUserName	接收方ID j2bxim
	 */
	public void messagesRecall(String token,String msgId,String toUserName) {
		try {
			String url = "https://a1.easemob.com/1126220315114898/kuoyou/messages/recall";
			RequestConfig config = RequestConfig.custom().setConnectTimeout(60000).setSocketTimeout(15000).build();
			HttpClient httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
			HttpPost httppost = new HttpPost(url);
			httppost.addHeader("Content-type","application/json;charset=UTF-8");
			httppost.addHeader("Authorization","Bearer "+token);
			JSONObject body = new JSONObject();
			JSONArray array = new JSONArray();
			JSONObject msgs = new JSONObject();
			msgs.put("msg_id", msgId);
			msgs.put("to", toUserName);
			msgs.put("chat_type", "chat");
			array.add(msgs);
			body.put("msgs", array);
			StringEntity entity = new StringEntity(body.toString());    
			httppost.setEntity(entity);
			HttpResponse execute = httpClient.execute(httppost);
			System.out.println(EntityUtils.toString(execute.getEntity(),"UTF-8"));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void main1(String[] args) throws Exception {
		//		String url = "https://a1.easemob.com/1126220315114898/demo/messages/recall";
		//		MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
		//		headers.add("Authorization", "Bearer YWMtRy5WctqPEeylGEORKlsdjgQfIf__MjPQu-0JvrjULpQU0UQdlNRNh4WlLDFBsiIEAgMAAAGA8MXuUDeeSACyZ0FjISawI6ttLCioJ11YQN7cWccuoOQ9kvC91702Kg");
		//		RestTemplate restTemplate = new RestTemplate();
		//		JSONObject body = new JSONObject();
		//		JSONArray array = new JSONArray();
		//		JSONObject msgs = new JSONObject();
		//		msgs.put("msg_id", "1012510754600913652");
		//		msgs.put("to", "j2bxim");
		//		msgs.put("chat_type", "chat");
		//		array.add(msgs);
		//		body.put("msgs", array);
		//        HttpEntity httpEntity = new HttpEntity(body.toString(),headers);
		//        ResponseEntity<DistinguishResult> tokenResponseEntity = restTemplate.postForEntity(url, httpEntity, DistinguishResult.class);
		//        System.out.println(tokenResponseEntity);
	}


}
